classdef ET_DS_SACCADE < ET_SS_CYCLIC
    % This class defines an experiment of double step saccade
    
    properties
        
        % Target1
        target1 = struct('w',0.25, ... Target width in degrees
            'h',0.25, ... Target width in degrees
            'color', [255 255 255], ... % Color of the target
            'ecc', 10, ... Degrees of eccentricity in x axis
            'shape', 'FillOval')
        
        
        % Target2
        target2 = struct('w',0.25, ... Target width in degrees
            'h',0.25, ... Target width in degrees
            'color', [255 255 255], ... % Color of the target
            'ecc', 10, ... Degrees of eccentricity in x axis
            'shape', 'FillOval')
        
        % Presentation times in seconds of the first and second target
        pt = [1,1;0.01,0.05]'
        % Calibration tolerance rate in dva
        tol_cal = 0.9
        % Time to test the calibration in secs
        test_cal_t = 0.8
        
    end
    
    
    methods
        
        function self = ET_DS_SACCADE()
            % New default. I Hate to do this kind of things
            % Fixation
            self.fix = struct('w',0.25, ... Fixation width in degrees.
            'h',0.25, ... fixation width in degrees
            'color', [255 255 255], ... % Color of the target
            'eccx', 5, ... Degrees of eccentricity in x axis
            'eccy', -5, ... Degrees of eccentricity in y axis
            'shape','FillOval');
            self.target = [];
        end
        
        function prepareBlock(self,blocks)
            % Prepares the blocks. In this case blocks indicate conditions.
            % It should be a list of number from one to three
            
            self.num_blocks = numel(blocks);
            self.blocks = blocks;
            
        end
        
        function prepareTrials(self,nt)
            % Prepares a matrix of the trials using information about the
            % number of the trials.
            %
            %   NT      Total number of trials displayed per block.
            %   JS      Jump size. It specifies the size of the target jump
            %           or displacement.
            
            % Counter balance left and right hemifield and left and right
            % movement of target.
            
            self.num_trials = nt;
            %t = repmat((1:8)',nt / 8,self.num_blocks);
            t = repmat([1 1 1 1 8 8 8 8]',nt / 8,self.num_blocks);
            self.trials = struct('t1x',num2cell(t),'t1y',0,...
                't2x',0,'t2y',0);

            for i = 1 : self.num_blocks
                t = [self.trials(randperm(nt),i).t1x];
                for j = 1:nt
                    self.trials(j,i).t1x = t(j);
                end
            end
            
            % Randomized 8 posibilities
            
            for i = 1:numel(self.trials)
                switch self.trials(i).t1x
                    case 1
                        self.trials(i).t1x = -self.target1.ecc;
                        self.trials(i).t1y = 0;
                        self.trials(i).t2x = -self.target2.ecc;
                        self.trials(i).t2y = -self.target2.ecc;
                    case 2
                        self.trials(i).t1x = 0;
                        self.trials(i).t1y = -self.target1.ecc;
                        self.trials(i).t2x = -self.target2.ecc;
                        self.trials(i).t2y = -self.target2.ecc;
                    case 3
                        self.trials(i).t1x = 0;
                        self.trials(i).t1y = -self.target1.ecc;
                        self.trials(i).t2x = self.target2.ecc;
                        self.trials(i).t2y = -self.target2.ecc;
                    case 4
                        self.trials(i).t1x = self.target2.ecc;
                        self.trials(i).t1y = 0;
                        self.trials(i).t2x = self.target2.ecc;
                        self.trials(i).t2y = -self.target2.ecc;
                    case 5
                        self.trials(i).t1x = self.target2.ecc;
                        self.trials(i).t1y = 0;
                        self.trials(i).t2x = self.target2.ecc;
                        self.trials(i).t2y = self.target2.ecc;                        
                    case 6
                        self.trials(i).t1x = 0;
                        self.trials(i).t1y = self.target2.ecc;
                        self.trials(i).t2x = self.target2.ecc;
                        self.trials(i).t2y = self.target2.ecc;                        
                    case 7
                        self.trials(i).t1x = 0;
                        self.trials(i).t1y = self.target2.ecc;
                        self.trials(i).t2x = -self.target2.ecc;
                        self.trials(i).t2y = self.target2.ecc;
                    case 8
                        self.trials(i).t1x = -self.target2.ecc;
                        self.trials(i).t1y = 0;
                        self.trials(i).t2x = -self.target2.ecc;
                        self.trials(i).t2y = self.target2.ecc;
                end
            end
            
            % Randomized conditions
            self.cond = repmat([2,2]',nt/2,self.num_blocks);
            
            for i = 1:self.num_blocks
                self.cond(:,i) = self.cond(randperm(nt),i);
            end
            
        end
        function [ok,goout] = expLoop_(self,trial)
            if self.cond(trial) == 1
                [ok,goout] = self.expLoopc1(trial);
            elseif self.cond(trial) == 2
                [ok,goout] = self.expLoopc2(trial);
            end
        end
        
        function [ok,goout] = expLoopc1(self,trial)
            
            % Runs the main experimental loop under the first condition
            %
            % TRIAL     Trial number.
            
            [t,b_] = ind2sub([self.num_trials,self.num_blocks],trial);
            
            b = self.blocks(b_);
                        
            % Creates the four point coordinates for rendering the image.
            % Cx is the center of the objet in the x axis, w it's width and
            % h its height.
            
            sp_ = @(cx,cy,w,h) [ cx - w/2,cy - h/2,cx + w/2,cy + h/2];
            
            % degrees to pixels
            d2p = @(d) round(self.scn.dist*tand(d)*(self.scn.w/self.scn.wcm));
            p2d = @(p) atand((self.scn.wcm*p/self.scn.w)/self.scn.dist);
            
            % Fixation
            
            cxf = self.scn.w/2 + d2p(self.fix.eccx);
            cyf = self.scn.h/2 + d2p(self.fix.eccy);
            
            
            % Initilize Eyelink
            if self.EyeLink
                % open a file on the eyetracker
                el = EyelinkInitDefaults(self.scn.p);
                % First two characters identify subject, %second two block
                % and last four trial.
                Eyelink('Openfile', ...
                    sprintf('%02d%02d%04d',self.exp_par.sbj,b_,t));
                Eyelink('StartRecording');
                self.sendParameters(trial);
            end
            
            fix_init = inf; % Time since fixation started
            phase = 0; % phase of experiment.
            ok = 1; % Keep going or abort
            avail = 0; % Just in case.
            goout = 0; % Just in case.
            flip_t = zeros(1,3); % Time stampts of the flips
            cal = 0; % Do calibration
            
            % Clean stack and have a short buffer
            KbEventFlush();
            WaitSecs(0.2);
            
            
            % Display fixation
            % =====================================================
            Screen('FillRect',self.scn.p,self.bc(b).bg);
                        
            
            smp = sp_(cxf,cyf,d2p(self.fix.w),d2p(self.fix.h));
            Screen(self.fix.shape,self.scn.p,tc(),round(smp));
            smp = sp_(cxf,cyf,d2p(self.fix.w/5),d2p(self.fix.h/5));
            Screen(self.fix.shape,self.scn.p,self.bc(b).bg,round(smp));
            
            Screen( 'Flip',self.scn.p);
            
            % Fixation window center
            
            fx = [cxf,cyf];
            
            
            t0 = GetSecs();
            
            if isunix()
                Priority(1);
            elseif ispc()
                priorityLevel=MaxPriority(self.scn.p);
                Priority(priorityLevel);
            end
           
            w = [-d2p(self.fix_win),d2p(self.fix_win),d2p(self.fix_win),...
                    -d2p(self.fix_win)];
            % Check the keyboard only every 20 times.
            kp = 1;
            while ok
                % If the subject presses any key during the trial, it is
                % aborted This only affects the two fist phases of the
                % experiment. For performance this is done only every ten
                % cycles
                if kp == 20
                    avail = KbCheck();
                    if avail
                        if self.EyeLink
                            Eyelink('MESSAGE','ABORT TRIAL');
                        end
                        ok = 0;
                        break
                    end
                    kp = 1;
                else
                    kp = kp + 1;
                end
                
                if ~self.EyeLink
                    [mx,my] = GetMouse();
                elseif self.EyeLink
                    % get the sample in the form of an event structure
                    evt = Eyelink( 'NewestFloatSample');
                    % Get x and y from the eye selected
                    x = evt.gx(self.el_pointer.er+1);
                    y = evt.gy(self.el_pointer.er+1);
                    % do we have valid data and is the pupil visible?
                    if x~=el.MISSING_DATA && y~=el.MISSING_DATA
                        mx=x;
                        my=y;                        
                    else
                        continue
                    end
                else
                    continue
                end
                
                % Wait until the eye has fixated for more than 0.2 seconds
                % do accep fixation. If accepted wait other 0.3 secs and
                % start trial.
                                
                if phase == 0
                    inw = inwindow(fx,mx,my,w);
                    t = GetSecs();
                    if inw && t - fix_init >= 0.200
                        % Fixation accepted, now enter the next phases
                        phase = 1;
                    elseif inw &&  fix_init == inf
                        fix_init = GetSecs();
                    elseif ~inw && t - fix_init <= 0.200
                        % Subject fixated but moved his eyes before the
                        % fixation was accepted. Buffer time is restarted.
                        fix_init = inf;
                    end
                    continue
                end
                
                if phase == 1
                    inw = inwindow(fx,mx,my,w);
                    t = GetSecs();
                    if inw && t - fix_init >= 1
                        % Fixation was accepted. Now continue to next
                        % phase.
                        if self.EyeLink
                            % Phase two started
                            Eyelink('MESSAGE','PHASE 2');
                        end
                        phase = 2;
                    elseif inw && t - fix_init < 1
                        continue
                    elseif ~inw 
                        % The subject failed to fixate while the targe was
                        % displayed. It aborts the trial and goes to the
                        % next.
                        if self.EyeLink
                            Eyelink('MESSAGE','ABORT TRIAL');
                        end
                        ok = 0;
                        continue
                    end
                end
                
                % =====================================================
                % Start critical phase
                % =====================================================                
                
                
                % =====================================================
                % Fixation dissapears, cue for the eye movement. Diplay
                % first target
                % =====================================================
                
                
                if phase == 2
                    % First Target
                    cx = cxf + d2p(self.trials(trial).t1x);
                    cy = cyf + d2p(self.trials(trial).t1y);
                    smp = sp_(cx,cy,d2p(self.target1.w),d2p(self.target1.h));
                    Screen(self.target1.shape,self.scn.p,tc(),round(smp));
                    smp = sp_(cx,cy,d2p(self.target1.w/5),d2p(self.target1.h/5));
                    Screen(self.target1.shape,self.scn.p,self.bc(b).bg,round(smp));
                    % Flip after 40 milliseconds
                    [~,~,flip_t(1)] = Screen('Flip',self.scn.p);
                    phase = 3;
                    % How long does the subject has to land in the goal.
                    %t = GetSecs();
                    if self.EyeLink
                        % Phase two started
                        Eyelink('MESSAGE','PHASE 3');
                    end
                end
                
                % =====================================================
                % After an interval first target dissapears, second target
                % appears
                % =====================================================
                
                if phase == 3
                    
                    % Second Target
                    cx = cxf + d2p(self.trials(trial).t2x);
                    cy = cyf + d2p(self.trials(trial).t2y);
                    smp = sp_(cx,cy,d2p(self.target2.w),d2p(self.target2.h));
                    Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                    smp = sp_(cx,cy,d2p(self.target2.w/5),d2p(self.target2.h/5));
                    Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                    
                    % Wait 40 ms
                    while GetSecs() - flip_t(1) < 0.090; end
                    
                    [~,~,flip_t(2)] = Screen('Flip',self.scn.p);
                    if self.EyeLink
                        % Phase four started
                        Eyelink('MESSAGE','PHASE 4');
                    end
                    
                    %t = GetSecs();
                    phase = 4;
                    %end
                    %continue
                end
                
                
                % =====================================================
                % Everything dissapears try to detect if the subject
                % fixated to the first target
                % =====================================================
                
                if phase == 4
                    
                    % Wait 90 ms from the first flip
                    while GetSecs() - flip_t(1) < 0.140; end
                    
                    % Clear screen
                    [~,~,flip_t(3)] = Screen('Flip',self.scn.p);
                    if self.EyeLink
                        % Phase five started
                        Eyelink('MESSAGE','PHASE 5');
                    end
                    % Escape this pase
                    phase = 5;
                    % =================================================
                    % Prepare for next phase
                    % =================================================
                    % Set the initial time to zero
                    fix_init = 0;
                    continue
                end
                
                
                if phase == 5 
                    t0 = GetSecs();
                    phase = 6;
                    if self.EyeLink
                        Eyelink('MESSAGE','PHASE 6');
                    end
                    continue
                end
                                                               
                % =========================================================
                % Explicit calibration test
                % =========================================================
                
                if phase == 6
                    if GetSecs() - t > self.test_cal_t
                        
                        % Second Target
                        cx = cxf + d2p(self.trials(trial).t2x);
                        cy = cyf + d2p(self.trials(trial).t2y);
                        smp = sp_(cx,cy,d2p(self.target2.w),d2p(self.target2.h));
                        Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cx,cy,d2p(self.target2.w/5),d2p(self.target2.h/5));
                        Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 7');
                        end
                        
                        t = GetSecs();
                        phase = 7;
                        
                        % New window for the fixation detection
                        fx = [cx,cy];
                        w = [-d2p(self.tol_cal),d2p(self.tol_cal),...
                            d2p(self.tol_cal),-d2p(self.tol_cal)];
                    end
                    continue
                end
                
                if phase == 7
                    if GetSecs() - t > self.test_cal_t
                        % Test wheter the calibration is still working
                        if ~inwindow(fx,mx,my,w)
                            cal = 1;
                            ok = 0;
                            if self.EyeLink
                                Eyelink('MESSAGE','ABORT TRIAL');
                            end
                            fprintf(1,'Decalibration by: %0.2f, %0.2f\n',...
                                p2d(fx(1)-mx),p2d(fx(2)-my));
                        end
                        % First Target
                        cx = cxf + d2p(self.trials(trial).t1x);
                        cy = cyf + d2p(self.trials(trial).t1y);
                        smp = sp_(cx,cy,d2p(self.target1.w),d2p(self.target1.h));
                        Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cx,cy,d2p(self.target1.w/5),d2p(self.target1.h/5));
                        Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 8');
                        end
                        t = GetSecs();
                        phase = 8;
                        % New window
                        fx = [cx,cy];
                    end
                    continue
                end
                
                
                
                if phase == 8
                    if GetSecs() - t > self.test_cal_t
                        % Test wheter the calibration is still working                        
                        if ~inwindow(fx,mx,my,w)
                            cal = 1;
                            ok = 0;
                            
                            if self.EyeLink
                                Eyelink('MESSAGE','ABORT TRIAL');
                            end
                            fprintf(1,'Decalibration by: %0.2f, %0.2f',...
                                p2d(fx(1)-mx),p2d(fx(2)-my));
                        end
                        % Central fix
                        smp = sp_(cxf,cyf,d2p(self.fix.w),d2p(self.fix.h));
                        Screen(self.fix.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cxf,cyf,d2p(self.fix.w/5),d2p(self.fix.h/5));
                        Screen(self.fix.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 9');
                        end
                        
                        t = GetSecs();
                        phase = 9;
                    end
                    continue
                end
                
                if phase == 9
                    % Every thing went well.
                    if GetSecs() - t > 1
                        if self.EyeLink
                            Eyelink('MESSAGE','PHASE 10');
                            Eyelink('MESSAGE','TRIAL ACEPTED');
                        end
                        break
                    end
                    continue
                end
                
                
            end

           
            % Stop recording with the eyetracker
            if self.EyeLink
                Eyelink('Closefile');
                Eyelink('ReceiveFile');
            end
            
            if cal
                calibrateEL(self.scn.p,self.scn.mon,0,...
                    self.bc(b).bg,self.bc(b).tc);
            end
            
            if ~ok
                WaitSecs(1);
            end
            
            % Intertrial
            % =============================================================
            % Display a intertrial stimuli
            KbEventFlush();
            t = GetSecs();
            
            % Display a cross in the screen during the intertrail interval.
            self.centeredText('+',tc(),20);
            
            while 1 > GetSecs() - t
                % Pause Trial if key is pressed
                [avail,~,k] = KbCheck();
                if avail
                    KbEventFlush();
                    self.centeredText(['Press ''q'' to quit or ''c'' to calibrate.' ...
                        '\n Press any other key to continue. ']);
                    % Buffer.
                    WaitSecs(0.5);
                    while 1
                        [avail,~,k] = KbCheck();
                        if avail;
                            break
                        end
                    end
                    % If the key is q
                    if find(k) == KbName('q')
                        goout = 1;
                        break
                        % If it's v, calbrate
                    elseif find(k) == KbName('c')
                        calibrateEL(self.scn.p,self.scn.mon,0,...
                            self.bc(b).bg,self.bc(b).tc);
                    end
                    KbEventFlush();
                    break
                end
            end
            
            function fix = inwindow(cx,mx,my,fix_win)
                % determine if gx and gy are within fixation window
                if nargin < 4
                    fix_win = self.fix_win;
                end
                fix = all([mx > (cx(1) + fix_win(1))
                    my < (cx(2) + fix_win(2))
                    mx < (cx(1) + fix_win(3))
                    my > (cx(2) + fix_win(4))
                    ]);
                
            end
            
            
            function c = tc()
                % target color
                c = self.bc(b).tc;
            end
           
            
        end
        
        function [ok,goout] = expLoopc2(self,trial)
            
            % Runs the main experimental loop under the second condition
            %
            % TRIAL     Trial number.
            
            [t,b_] = ind2sub([self.num_trials,self.num_blocks],trial);
            
            b = self.blocks(b_);
                        
            % Creates the four point coordinates for rendering the image.
            % Cx is the center of the objet in the x axis, w it's width and
            % h its height.
            
            sp_ = @(cx,cy,w,h) [ cx - w/2,cy - h/2,cx + w/2,cy + h/2];
            
            % degrees to pixels
            d2p = @(d) round(self.scn.dist*tand(d)*(self.scn.w/self.scn.wcm));
            p2d = @(p) atand((self.scn.wcm*p/self.scn.w)/self.scn.dist);
            
            % Fixation
            
            cxf = self.scn.w/2 + d2p(self.fix.eccx);
            cyf = self.scn.h/2 + d2p(self.fix.eccy);
            
            
            % Initilize Eyelink
            if self.EyeLink
                % open a file on the eyetracker
                el = EyelinkInitDefaults(self.scn.p);
                % First two characters identify subject, %second two block
                % and last four trial.
                Eyelink('Openfile', ...
                    sprintf('%02d%02d%04d',self.exp_par.sbj,b_,t));
                Eyelink('StartRecording');
                self.sendParameters(trial);
            end
            
            fix_init = inf; % Time since fixation started
            phase = 0; % phase of experiment.
            ok = 1; % Keep going or abort
            avail = 0; % Just in case.
            goout = 0; % Just in case.
            flip_t = zeros(1,3); % Time stampts of the flips
            cal = 0;
            
            % Clean stack and have a short buffer
            KbEventFlush();
            WaitSecs(0.2);
            
            
            % Display fixation
            % =====================================================
            Screen('FillRect',self.scn.p,self.bc(b).bg);
                        
            
            smp = sp_(cxf,cyf,d2p(self.fix.w),d2p(self.fix.h));
            Screen(self.fix.shape,self.scn.p,tc(),round(smp));
            smp = sp_(cxf,cyf,d2p(self.fix.w/5),d2p(self.fix.h/5));
            Screen(self.fix.shape,self.scn.p,self.bc(b).bg,round(smp));
            
            Screen( 'Flip',self.scn.p);
            
            % Fixation window center
            
            fx = [cxf,cyf];
            
            
            t0 = GetSecs();
            
            if isunix()
                Priority(1);
            elseif ispc()
                priorityLevel=MaxPriority(self.scn.p);
                Priority(priorityLevel);
            end
            
            t_a = self.fix_buffer_t;
            w = [-d2p(self.fix_win),d2p(self.fix_win),d2p(self.fix_win),...
                    -d2p(self.fix_win)];
            % Check the keyboard only every 20 times.
            kp = 1;
            while ok
                % If the subject presses any key during the trial, it is
                % aborted This only affects the two fist phases of the
                % experiment. For performance this is done only every ten
                % cycles
                if kp == 20
                    avail = KbCheck();
                    if avail
                        if self.EyeLink
                            Eyelink('MESSAGE','ABORT TRIAL');
                        end
                        ok = 0;
                        break
                    end
                    kp = 1;
                else
                    kp = kp + 1;
                end
                
                if ~self.EyeLink
                    [mx,my] = GetMouse();
                elseif self.EyeLink
                    % get the sample in the form of an event structure
                    evt = Eyelink( 'NewestFloatSample');
                    % Get x and y from the eye selected
                    x = evt.gx(self.el_pointer.er+1);
                    y = evt.gy(self.el_pointer.er+1);
                    % do we have valid data and is the pupil visible?
                    if x~=el.MISSING_DATA && y~=el.MISSING_DATA
                        mx=x;
                        my=y;
                    else
                        continue
                    end
                else
                    continue
                end
                
                % Wait until the eye has fixated for more than 0.2 seconds
                % do accep fixation. If accepted wait other 0.3 secs and
                % start trial.
                
                if phase == 0
                    inw = inwindow(fx,mx,my,w);
                    t = GetSecs();
                    if inw && t - fix_init >= 0.200
                        % Fixation accepted, now enter the next phases
                        phase = 1;
                    elseif inw &&  fix_init == inf
                        fix_init = GetSecs();
                    elseif ~inw && t - fix_init <= 0.200
                        % Subject fixated but moved his eyes before the
                        % fixation was accepted. Buffer time is restarted.
                        fix_init = inf;
                    end
                    continue
                end
                
                if phase == 1
                    inw = inwindow(fx,mx,my,w);
                    t = GetSecs();
                    if inw && t - fix_init >= 1
                        % Fixation was accepted. Now continue to next
                        % phase.
                        if self.EyeLink
                            % Phase two started
                            Eyelink('MESSAGE','PHASE 2');
                        end
                        phase = 2;
                    elseif inw && t - fix_init < 1
                        continue
                    elseif ~inw 
                        % The subject failed to fixate while the targe was
                        % displayed. It aborts the trial and goes to the
                        % next.
                        if self.EyeLink
                            Eyelink('MESSAGE','ABORT TRIAL');
                        end
                        ok = 0;
                        continue
                    end
                end
                
                % =====================================================
                % Start critical phase
                % =====================================================                
                
                
                % =====================================================
                % Fixation dissapears, cue for the eye movement. Diplay
                % first target
                % =====================================================
                
                
                if phase == 2
                    % First Target
                    cx = cxf + d2p(self.trials(trial).t1x);
                    cy = cyf + d2p(self.trials(trial).t1y);
                    smp = sp_(cx,cy,d2p(self.target1.w),d2p(self.target1.h));
                    Screen(self.target1.shape,self.scn.p,tc(),round(smp));
                    smp = sp_(cx,cy,d2p(self.target1.w/5),d2p(self.target1.h/5));
                    Screen(self.target1.shape,self.scn.p,self.bc(b).bg,round(smp));
                    % Flip after 40 milliseconds
                    [~,~,flip_t(1)] = Screen('Flip',self.scn.p);
                    phase = 3;
                    % How long does the subject has to land in the goal.
                    %t = GetSecs();
                    if self.EyeLink
                        % Phase two started
                        Eyelink('MESSAGE','PHASE 3');
                    end
                    fx = [cx,cy];
                    w = [-d2p(2.5),d2p(2.5),d2p(2.5),-d2p(2.5)];
                end
                
                % =====================================================
                % After an interval first target dissapears
                % =====================================================
                
                if phase == 3

                    % Wait 90 ms
                    while GetSecs() - flip_t(1) < 0.090; end
                    
                    [~,~,flip_t(2)] = Screen('Flip',self.scn.p);
                    if self.EyeLink
                        % Phase four started
                        Eyelink('MESSAGE','PHASE 4');
                    end
                    phase = 4;
                    t = GetSecs();
                    continue
                end
                
                if phase == 4
                    
                    if inwindow(fx,mx,my,w) && GetSecs() - t < 0.350
                    t = GetSecs();
                                    
                    % Second Target
                    cx = cxf + d2p(self.trials(trial).t2x);
                    cy = cyf + d2p(self.trials(trial).t2y);
                    smp = sp_(cx,cy,d2p(self.target2.w),d2p(self.target2.h));
                    Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                    smp = sp_(cx,cy,d2p(self.target2.w/5),d2p(self.target2.h/5));
                    Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                    
                    [~,~,flip_tn] = Screen('Flip',self.scn.p);
                    if self.EyeLink
                        % Phase four started
                        Eyelink('MESSAGE','PHASE 5');
                    end
                    
                    phase = 5;
                    
                    elseif ~inwindow(fx,mx,my,w) && GetSecs() - t > 0.350
                            ok = 0;
                            
                            if self.EyeLink
                                Eyelink('MESSAGE','ABORT TRIAL');
                            end
                        
                    
                    end
                    continue
                end
                % =====================================================
                % Everything dissapears try to detect if the subject
                % fixated to the first target
                % =====================================================
                
                if phase == 5
                    
                    % Wait 50 ms from the first flip
                    while GetSecs() - flip_tn < 0.040; end
                    
                    % Clear screen
                    [~,~,flip_t(3)] = Screen('Flip',self.scn.p);
                    if self.EyeLink
                        % Phase five started
                        Eyelink('MESSAGE','PHASE 6');
                    end
                    % Escape this pase
                    phase = 6;
                    t = GetSecs();
                    continue
                end
                
                                                               
                % =========================================================
                % Explicit calibration test
                % =========================================================
                
                if phase == 6
                    if GetSecs() - t > self.test_cal_t
                        
                        % Second Target
                        cx = cxf + d2p(self.trials(trial).t2x);
                        cy = cyf + d2p(self.trials(trial).t2y);
                        smp = sp_(cx,cy,d2p(self.target2.w),d2p(self.target2.h));
                        Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cx,cy,d2p(self.target2.w/5),d2p(self.target2.h/5));
                        Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 7');
                        end
                        
                        t = GetSecs();
                        phase = 7;
                        
                        % New window for the fixation detection
                        fx = [cx,cy];
                        w = [-d2p(self.tol_cal),d2p(self.tol_cal),...
                            d2p(self.tol_cal),-d2p(self.tol_cal)];
                    end
                    continue
                end
                
                if phase == 7
                    if GetSecs() - t > self.test_cal_t
                        % Test wheter the calibration is still working
                        if ~inwindow(fx,mx,my,w)
                            cal = 1;
                            ok = 0;
                            if self.EyeLink
                                Eyelink('MESSAGE','ABORT TRIAL');
                            end
                            fprintf(1,'Decalibration by: %0.2f, %0.2f\n',...
                                p2d(fx(1)-mx),p2d(fx(2)-my));
                        end
                        % First Target
                        cx = cxf + d2p(self.trials(trial).t1x);
                        cy = cyf + d2p(self.trials(trial).t1y);
                        smp = sp_(cx,cy,d2p(self.target1.w),d2p(self.target1.h));
                        Screen(self.target2.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cx,cy,d2p(self.target1.w/5),d2p(self.target1.h/5));
                        Screen(self.target2.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 8');
                        end
                        t = GetSecs();
                        phase = 8;
                        % New window
                        fx = [cx,cy];
                    end
                    continue
                end
                
                
                
                if phase == 8
                    if GetSecs() - t > self.test_cal_t
                        % Test wheter the calibration is still working                        
                        if ~inwindow(fx,mx,my,w)
                            cal = 1;
                            ok = 0;
                            
                            if self.EyeLink
                                Eyelink('MESSAGE','ABORT TRIAL');
                            end
                            fprintf(1,'Decalibration by: %0.2f, %0.2f',...
                                p2d(fx(1)-mx),p2d(fx(2)-my));
                        end
                        % Central fix
                        smp = sp_(cxf,cyf,d2p(self.fix.w),d2p(self.fix.h));
                        Screen(self.fix.shape,self.scn.p,tc(),round(smp));
                        smp = sp_(cxf,cyf,d2p(self.fix.w/5),d2p(self.fix.h/5));
                        Screen(self.fix.shape,self.scn.p,self.bc(b).bg,round(smp));
                        Screen('Flip',self.scn.p);
                        if self.EyeLink
                            % Phase four started
                            Eyelink('MESSAGE','PHASE 9');
                        end
                        
                        t = GetSecs();
                        phase = 9;
                    end
                    continue
                end
                
                if phase == 9
                    % Every thing went well.
                    if GetSecs() - t > 1
                        if self.EyeLink
                            Eyelink('MESSAGE','PHASE 10');
                            Eyelink('MESSAGE','TRIAL ACEPTED');
                        end
                        break
                    end
                    continue
                end
                
                
            end

           
            % Stop recording with the eyetracker
            if self.EyeLink
                Eyelink('Closefile');
                Eyelink('ReceiveFile');
            end
            
            if cal
                calibrateEL(self.scn.p,self.scn.mon,0,...
                    self.bc(b).bg,self.bc(b).tc);
            end
            
            if ~ok
                WaitSecs(1);
            end
            
            % Intertrial
            % =============================================================
            % Display a intertrial stimuli
            KbEventFlush();
            t = GetSecs();
            
            % Display a cross in the screen during the intertrail interval.
            self.centeredText('+',tc(),20);
            
            while 1 > GetSecs() - t
                % Pause Trial if key is pressed
                [avail,~,k] = KbCheck();
                if avail
                    KbEventFlush();
                    self.centeredText(['Press ''q'' to quit or ''c'' to calibrate.' ...
                        '\n Press any other key to continue. ']);
                    % Buffer.
                    WaitSecs(0.5);
                    while 1
                        [avail,~,k] = KbCheck();
                        if avail;
                            break
                        end
                    end
                    % If the key is q
                    if find(k) == KbName('q')
                        goout = 1;
                        break
                        % If it's v, calbrate
                    elseif find(k) == KbName('c')
                        calibrateEL(self.scn.p,self.scn.mon,0,...
                            self.bc(b).bg,self.bc(b).tc);
                    end
                    KbEventFlush();
                    break
                end
            end
            
            function fix = inwindow(cx,mx,my,fix_win)
                % determine if gx and gy are within fixation window
                if nargin < 4
                    fix_win = self.fix_win;
                end
                fix = all([mx > (cx(1) + fix_win(1))
                    my < (cx(2) + fix_win(2))
                    mx < (cx(1) + fix_win(3))
                    my > (cx(2) + fix_win(4))
                    ]);
                
            end
            
            
            function c = tc()
                % target color
                c = self.bc(b).tc;
            end
            
        end
        
        
        function sendParameters(self,trial)
            % Send information to the eyetracker which is worth to store.
            
            % degrees to pixels
            d2p = @(d) round(self.scn.dist*tand(d)*(self.scn.w/self.scn.wcm));
            
            % Fixation
            
            cxf = self.scn.w/2 + d2p(self.fix.eccx);
            cyf = self.scn.h/2 + d2p(self.fix.eccy);
            
            [t,b] = ind2sub([self.num_trials self.num_blocks],trial);
            Eyelink('Message',['BLOCK ' num2str(self.blocks(b))]);
            Eyelink('Message',['TRIAL ' num2str(t)]);
            Eyelink('Message',['SUBJECT ' num2str(self.exp_par.sbj)]);
            Eyelink('Message',sprintf('AMPT1X %0.4f',...
                cxf + d2p(self.trials(trial).t1x)));
            Eyelink('Message',sprintf('AMPT1Y %0.4f',...
                cyf + d2p(self.trials(trial).t1y)));
            WaitSecs(0.1);
            Eyelink('Message',sprintf('AMPT2X %0.4f',...
                cxf + d2p(self.trials(trial).t2x)));
            Eyelink('Message',sprintf('AMPT2Y %0.4f',...
                cyf + d2p(self.trials(trial).t2y)));
            Eyelink('Message',sprintf('FIXX %0.4f',cxf));
            Eyelink('Message',sprintf('FIXY %0.4f',cyf));
            Eyelink('Message',sprintf('COND %d',self.cond(trial)));
        end
    end
end